package com.gitee.huxing.framework.core;

import com.alibaba.fastjson.JSON;
import com.gitee.huxing.framework.core.filter.Filter;
import com.gitee.huxing.framework.core.module.RequestInfo;
import com.gitee.huxing.framework.core.module.ResponseInfo;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * @Description:
 * @ProjectName: JavaCourse
 * @Package: com.gitee.huxing.framework.core
 * @ClassName: ServiceInvocationHandler
 * @Author: huxing
 * @DateTime: 2021-09-29 上午10:40
 */
@Slf4j
public class ServiceInvocationHandler<T> extends AbstractInvokeHandler implements InvocationHandler {

    public ServiceInvocationHandler(Class<T> serviceClass, String url, Filter[] filters) {
        super(serviceClass, url, filters);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] params) throws Throwable {
        return this.postMethod(method, params);
    }

    /**
     * @Description: http请求业务处理
     * @Author: huxing
     * @param method   方法
     * @param params   参数
     * @return java.lang.Object
     * @Date: 2021/10/8 下午12:56
     **/
    public Object postMethod(Method method, Object[] params) throws Throwable{
        // 初始化业务请求对象
        RequestInfo request = new RequestInfo();
        request.setServiceClass(this.serviceClass.getName());
        request.setMethod(method.getName());
        request.setParams(params);

        // 过滤处理
        if (null!=filters){
            for (Filter filter:filters){
                if (!filter.filter(request)){
                    return null;
                }
            }
        }
        // 调用接口处理请求对象 - 增加错误捕捉，返回错误提示
        ResponseInfo response = this.post(request, url);
        // 返回结果提示
        return JSON.parse(response.getResult().toString());
    }
}
